var ctx=window.daijia.ctx;
var lng=window.daijia.lng;
var lat=window.daijia.lat;
var map = null;
var paidanMap = null;
var order = null;
var moreFlag = false;
var driving = null;
var distance=[];
var timeStr=[];
var points=[];
var flag=true;
var tempmarkers=[];
var polylines=[];
var index = 0;
var myGeo = null;
var car=null;
var pointObj=[];
var orbitCar=null;
var timer;     //定时器
var index = 0; //记录播放到第几个point
var orbitpoints=[];
var firstpoint=null;
var lastpoint=null;
var isfirst=true;
var vectorMarker=null;
function initialize(){
	    myGeo = new BMap.Geocoder();
	var point=new BMap.Point(lng,lat);
	if (point) {
		map = new BMap.Map("map");
		$(".anchorBL").remove();
		map.centerAndZoom(point, 13);
	    map.enableScrollWheelZoom();
	    map.addEventListener("tilesloaded",function(){
	    	$(".anchorBL").remove();
	    });
	    var ctrl = new BMapLib.TrafficControl({
	           showPanel: true //是否显示路况提示面板
	       });      
	       map.addControl(ctrl);
	       ctrl.setAnchor(BMAP_ANCHOR_TOP_LEFT);  
	    map.addControl(new BMap.MapTypeControl({anchor: BMAP_ANCHOR_TOP_RIGHT, mapTypes: [BMAP_NORMAL_MAP,BMAP_HYBRID_MAP]}));
	    
	    map.addControl(new BMap.NavigationControl({anchor: BMAP_ANCHOR_BOTTOM_RIGHT, type: BMAP_NAVIGATION_CONTROL_SMALL}));  //右上角，仅包含平移和缩放按钮
	    ///三种驾车策略：最少时间，最短距离，避开高速    BMAP_freight_driving_POLICY_LEAST_TIME,BMAP_freight_driving_POLICY_LEAST_DISTANCE,BMAP_freight_driving_POLICY_AVOID_HIGHWAYS
	    driving = new BMap.DrivingRoute(map, {policy : BMAP_DRIVING_POLICY_LEAST_DISTANCE});
	    driving.setSearchCompleteCallback(function(){
	        var pts = driving.getResults().getPlan(0).getRoute(0).getPath(); //通过驾车实例，获得一系列点的数组
	        var plan = driving.getResults().getPlan(0);
	        distance[distance.length]=plan.getDistance(true);
	        timeStr[timeStr.length]=plan.getDuration(true);
	        
	        var polyline = new BMap.Polyline(pts); 
	        polyline.setStrokeColor("#01BC00");
	        polylines[polylines.length]=polyline;
	        map.addOverlay(polyline);
	        if(flag){
	        	bdGEO();
	        	flag=false;
	        }
	       setTimeout(function(){
	            map.setViewport(points); 
	            //调整到最佳视野
	        },200);
	    });
	   
	}else{
		$.scojs_message("地区"+center+"位置不准确，请重新编辑地区", $.scojs_message.TYPE_ERROR);
	}
}

function orbitInit(){
	
	if(isfirst){
		
		$.post(ctx+'/freight/pointDetails',{'id':order.id},function(data){
			if(data.success){
	               if(null!=data.firstLng && null!=data.firstLat){
	               
	               		$("#run_distance_span").html(data.runDistance+"公里");
	               		$("#wait_distance_span").html(data.waitDistance+"公里");
	               		
						firstpoint=new BMap.Point(data.firstLng, data.firstLat);
	               
						map.centerAndZoom(firstpoint, 12);
					    map.enableScrollWheelZoom();
	               		
	               		var pointmap=data.orderLocations;
	               		
	               		var pointsDiv="";
	               		
	               		pointsDiv+="<div class='list-group' style='margin-bottom: 0px;'>";
	               		pointsDiv+="<a href='JavaScript:;' class='list-group-item'>定位时间<div style='float:right'>类型</div></a>";
	               		pointsDiv+="<a href='JavaScript:;' class='list-group-item' style='text-align:center;'>（类型为GPS才准确）</a>";
	               		var lastLng=null;
        				var lastlat=null;
	               		$(pointmap).each(function(index,element){
	               			points.push(new BMap.Point(element.longitude, element.latitude));
	               			pointsDiv+="<a href='JavaScript:;' class='list-group-item points_click' data-lng='"+element.longitude+"' data-lat='"+element.latitude+"' data-locDate='"+element.locDateSecondsStr+"' data-locType='"+element.locTypeStr+"' data-radius='"+element.radius+"'>"+element.locDateSecondsStr+"<div style='float:right'>"+element.locTypeStr+"</div></a>";
            				var thisLng=element.longitude;
            				var thislat=element.latitude;
            				if(null!=thisLng && null!=thislat && null!=lastLng && null!=lastlat){
            					var thisPoints=[];
            					thisPoints.push(new BMap.Point(thisLng, thislat));
            					thisPoints.push(new BMap.Point(lastLng, lastlat));
            					if(element.run==1){
            						map.addOverlay(new BMap.Polyline(thisPoints, {strokeColor: "red", strokeWeight: 8, strokeOpacity: 1}));
            					}
            					else{
            						map.addOverlay(new BMap.Polyline(thisPoints, {strokeColor: "#ff8a18", strokeWeight: 8, strokeOpacity: 0.8}));
            					}
            				}
	               			lastLng=thisLng;
	               			lastlat=thislat;
	               		});
	               		pointsDiv+="</div>";
	               		orbitpoints = points;
	               		
	               		$("#points_div").html(pointsDiv);
			        
			     //   map.addOverlay(new BMap.Polyline(orbitpoints, {strokeColor: "blue", strokeWeight: 5, strokeOpacity: 1}));
			
					//显示小车子
					orbitCar = new BMap.Marker(orbitpoints[0]);
					map.addOverlay(orbitCar);
					
					$("#playcar").show();
					$("#resetcar").show();
					$("#distancetool").show();
					$("#playcar").attr("disabled",false);
					$("#resetcar").attr("disabled",false);
						
               }
               else{
               		$("#points_div").html("<div class='panel-body'>暂无订单轨迹</div>");
               }
            } else {
                $.scojs_message(data.message, $.scojs_message.TYPE_ERROR);
            }
	    },'json');
	    isfirst=false;
	    
	}
    
}

function play() {
	$("#playcar").attr("disabled",true);
	$("#resetcar").attr("disabled",false);
	
	var point = orbitpoints[index];
	if(index > 0) {
		map.addOverlay(new BMap.Polyline([orbitpoints[index - 1], point], {strokeColor: "#0185da", strokeWeight: 5, strokeOpacity: 0.7}));
	}
	orbitCar.setPosition(point);
	index++;
	
	if(index < orbitpoints.length) {
		timer = window.setTimeout("play(" + index + ")", 100);
	} else {
		$("#playcar").attr("disabled",true);
		map.panTo(point);
	}
}

function reset() {
	$("#playcar").attr("disabled",false);
	
	if(timer) {
		window.clearTimeout(timer);
	}
	index = 0;
	orbitCar.setPosition(orbitpoints[0]);
	map.panTo(firstpoint);
}
var deFlag=true;
function bdGEO(){
	if(deFlag){
		var pt = points[index];
		geocodeSearch(pt);
		index++;
	}
	
}
$(document).on("mouseover",".points_click",function(){
	$(".points_click").removeClass("active");
	$(this).addClass("active");
	if(null!=map){
		if(null!=vectorMarker){
			vectorMarker.remove();
		}
		var this_point=new BMap.Point($(this).attr("data-lng"), $(this).attr("data-lat"));
		vectorMarker = new BMap.Marker(this_point, {
		  // 指定Marker的icon属性为Symbol
		  icon: new BMap.Symbol(BMap_Symbol_SHAPE_POINT, {
		    scale: 1,//图标缩放大小
		    fillColor: "orange",//填充颜色
		    fillOpacity: 1//填充透明度
		  })
		});
		
		var opts = {
		  width : 200,     // 信息窗口宽度
		  height: 120,     // 信息窗口高度
		  title : "<b>轨迹详情</b>",  // 信息窗口标题
		  offset : new BMap.Size(0, -25)
		}
		var sContent="";
		sContent+="经度："+$(this).attr("data-lng")+"<br/>";
		sContent+="纬度："+$(this).attr("data-lat")+"<br/>";
		sContent+="定位时间："+$(this).attr("data-locDate")+"<br/>";
		sContent+="类型："+$(this).attr("data-loctype")+"<br/>";
		sContent+="精度："+$(this).attr("data-radius")+"<br/>";
		var infoWindow = new BMap.InfoWindow(sContent, opts);  // 创建信息窗口对象 
		map.openInfoWindow(infoWindow,this_point); //开启信息窗口

		map.addOverlay(vectorMarker);
	}
});

function geocodeSearch(pt){
	deFlag=false;
	if(index < points.length-1){
		setTimeout(window.bdGEO,500);
	} 
	myGeo.getLocation(pt, function(rs){
		deFlag=true;
		if(index==1){
			var addComp = rs.addressComponents;
			var myIcon = new BMap.Icon(ctx+"/assets/img/start.png", new BMap.Size(32,32));
		//	var myIcon = new BMap.Icon("http://developer.baidu.com/map/jsdemo/img/fox.gif", new BMap.Size(32,32));
			var m = new BMap.Marker(pt,{icon:myIcon});
			tempmarkers[tempmarkers.length]=m;
			var  str= addComp.district + " " + addComp.street;
			/*var lab = new BMap.Label(str,{offset:new BMap.Size(-30,-15)});
			lab.setStyle({ color : "#ED2D2D", fontSize : "16px",border:"0" });
			m.setLabel(lab);*/
			map.addOverlay(m);
			var opts = {
					  width : 160,     // 信息窗口宽度
					  height: 75,     // 信息窗口高度
					//  title :  , // 信息窗口标题
					  enableMessage:true,//设置允许信息窗发送短息
					  message:"亲耐滴，晚上一起吃个饭吧？戳下面的链接看下地址喔~"
					}
					var infoWindow = new BMap.InfoWindow("地址:"+str+"<br/>联系人:"+pointObj[0].contacts+"<br/>联系电话:"+pointObj[0].phone+"<br/>"+(pointObj[index-1].arrive?("时间:"+new Date(pointObj[index-1].arriveTime).Format("yyyy/MM/dd hh:mm")):""), opts);  // 创建信息窗口对象 
					m.addEventListener("click", function(){          
						map.openInfoWindow(infoWindow,pt); //开启信息窗口
					});
			
			
		}else if(index==points.length){
			var addComp = rs.addressComponents;
			var myIcon = new BMap.Icon(ctx+"/assets/img/end.png", new BMap.Size(50,32));
			//var myIcon = new BMap.Icon("http://developer.baidu.com/map/jsdemo/img/fox.gif", new BMap.Size(300,157));
			var m = new BMap.Marker(pt,{icon:myIcon});
			tempmarkers[tempmarkers.length]=m;
			var  str= addComp.district + " " + addComp.street;
			/*var lab = new BMap.Label(str,{offset:new BMap.Size(-30,-15)});
			lab.setStyle({ color : "#ED2D2D", fontSize : "16px",border:"0" });
			m.setLabel(lab);*/
			map.addOverlay(m);
			var opts = {
					  width : 160,     // 信息窗口宽度
					  height: 75,     // 信息窗口高度
					//  title :  , // 信息窗口标题
					  enableMessage:true,//设置允许信息窗发送短息
					  message:"亲耐滴，晚上一起吃个饭吧？戳下面的链接看下地址喔~"
					}
					var infoWindow = new BMap.InfoWindow("地址:"+str+"<br/>联系人:"+pointObj[pointObj.length-1].contacts+"<br/>联系电话:"+pointObj[pointObj.length-1].phone+"<br/>"+(pointObj[index-1].arrive?("时间:"+new Date(pointObj[index-1].arriveTime).Format("yyyy/MM/dd hh:mm")):""), opts);  // 创建信息窗口对象 
					m.addEventListener("click", function(){          
						map.openInfoWindow(infoWindow,pt); //开启信息窗口
					});
		}else{
			var addComp = rs.addressComponents;
			var myIcon = new BMap.Icon(ctx+"/assets/img/waypoints"+(index-1)+".png", new BMap.Size(36,32));
			//var myIcon = new BMap.Icon("http://developer.baidu.com/map/jsdemo/img/fox.gif", new BMap.Size(300,157));
			var m = new BMap.Marker(pt,{icon:myIcon});
			tempmarkers[tempmarkers.length]=m;
			var  str= addComp.district + " " + addComp.street;
			/*var lab = new BMap.Label(str,{offset:new BMap.Size(-30,-15)});
			lab.setStyle({ color : "#ED2D2D", fontSize : "16px",border:"0" });
			m.setLabel(lab);*/
			map.addOverlay(m);
			var opts = {
					  width : 160,     // 信息窗口宽度
					  height: 75,     // 信息窗口高度
					//  title :  , // 信息窗口标题
					  enableMessage:true,//设置允许信息窗发送短息
					  message:"亲耐滴，晚上一起吃个饭吧？戳下面的链接看下地址喔~"
					}
					var infoWindow = new BMap.InfoWindow("地址:"+str+"<br/>联系人:"+pointObj[index-1].contacts+"<br/>联系电话:"+pointObj[index-1].phone+"<br/>"+(pointObj[index-1].arrive?("时间:"+new Date(pointObj[index-1].arriveTime).Format("yyyy/MM/dd hh:mm")):""), opts);  // 创建信息窗口对象 
					m.addEventListener("click", function(){          
						map.openInfoWindow(infoWindow,pt); //开启信息窗口
					});
		}
		
	});
	 
}
function getDriver(){ 
	var employId=order.employId;
	if(order.employId!=null){
		$.get(ctx+'/freight/getEmploy',{'employId':employId},function(data){
			if(data.lng!=null&&data.lat!=null){
				var lng = data.lng;
				var lat = data.lat;
				var point=new BMap.Point(lng,lat);
				map.removeOverlay(car);
				var myIcon = new BMap.Icon(ctx+"/assets/img/car.png", new BMap.Size(32,46));
				//var myIcon = new BMap.Icon("http://developer.baidu.com/map/jsdemo/img/fox.gif", new BMap.Size(300,157));
				 car = new BMap.Marker(point,{icon:myIcon});
				map.addOverlay(car);
			}
		});	
	}
} 

$(function(){
	initialize();
	
	$("#distancetool").click(function(){
		var myDis = new BMapLib.DistanceTool(map);
		myDis.open();
		
	});
	$.get(ctx+'/freight/orderDetailsData',{'orderId':orderId},function(data){
		order=data.order;
		
		if(order.status!=5){
			if(data!=null&&data.order!=null&&data.order.waypoints!=null){
				for(var i=0;i<order.waypoints.length;i++){
					points[points.length] = new BMap.Point(order.waypoints[i].lng,order.waypoints[i].lat);
					pointObj[pointObj.length]=order.waypoints[i];
				}
				map.clearOverlays();
				  flag=true;
				  index=0;
				  distance=[];
				  timeStr=[];
				  
				 for(var i=0;i<points.length-1;i++){
					  driving.search(points[i],points[i+1]);
				  }
				 if(order.status!=5&&order.status!=6&&order.status!=0){
					 getDriver();
					 window.setInterval("getDriver()",1000); 
				 }
			}
		}else if(order.status==5){
			$("#orbit").css("display","block");
			orbitInit();
		}
		
	},'json');
	
	
	$(document).on("click",".more",function(){
		var status = order.orderStatusList;
		var str="";
		var first ="";
		$("#moreDetail").empty();
		if(!moreFlag){
			//$(this).attr("src",ctx+"/assets/img/up.png");
			for(var i=0;i<status.length;i++){
			    if(i==(status.length-1)){
			     str += "<li style='list-style:none;padding-left:20px;'><div class='row'><div class='col-sm-12'>"+new Date(status[i].created).Format("MM月dd hh:mm")+"<span>"+status[i].memo+"</span></div></div></li>";
			     str+="<li style='list-style:none;'><center><div><img class='more' src='"+ctx+"/assets/img/up.png'/></div></center></li>";
			    }else{
			     str += "<li style='list-style:none;padding-left:20px;'><div class='row'><div class='col-sm-12'>"+new Date(status[i].created).Format("MM月dd hh:mm")+"<span>"+status[i].memo+"</span></div></div></li>";
			    }
			}
			$("#moreDetail").append(str);
			moreFlag=true;
		}else{
			/*$(this).attr("src",ctx+"/assets/img/down.png");
			$("#moreDetail").empty();*/
			var first = "<li style='list-style:none;padding-left:20px;'><div class='row'><div class='col-sm-10'>下单时间："+new Date(status[0].created).Format("MM月dd hh:mm")+"<span>"+status[0].memo+"</span></div><div class='col-sm-1'><img class='more'  src='"+ctx+"/assets/img/down.png'/></div></div></li>";
			$("#moreDetail").append(first);
			moreFlag=false;
		}
	});
	
});
//派单
var startLng;
var startLat;
var clientName;
var clientPhone;
var startAddress;
var truckTypeName;
$(document).on("click",".freight_detail_paidan",function(){
	startLng=$(this).attr("startLng");
	startLat=$(this).attr("startLat");
	clientName=$(this).attr("clientName");
	clientPhone=$(this).attr("clientPhone");
	startAddress=$(this).attr("startAddress");
	truckTypeName=$(this).attr("truckTypeName");
	$("#paidanOrderId").val($(this).attr("orderId"));
	$("#paidanClientName").html("");
	$("#paidanClientPhone").html("");
	$("#paidanFromPlace").html("");
	$("#truckTypeName").html("");
	$("#dialog_paidan").modal();
});

$('#dialog_paidan').on('shown.bs.modal', function () {
	$("#paidanOrderLng").val(startLng);
	$("#paidanOrderLat").val(startLat);
	$("#paidanClientName").html(clientName);
	$("#paidanClientPhone").html(clientPhone);
	$("#paidanFromPlace").html(startAddress);
	$("#truckTypeName").html(truckTypeName);
	showClientMaker(startLng,startLat);
	getDrivers(startLng,startLat);
});
$('#distance').change(function(){
	showClientMaker($("#paidanOrderLng").val(),$("#paidanOrderLat").val());
	getDrivers($("#paidanOrderLng").val(),$("#paidanOrderLat").val());
});
$(document).on("click",".f_detail_paigeita",function(){
	var driverId=$(this).attr("data-id");
	if(window.confirm('确认要派单给该服务人员吗？')){
		$.post(ctx+'/freight/paidan',{'driverId':driverId,'orderId':$("#paidanOrderId").val()},function(data){
			if(data.success){
				$.scojs_message("派单成功", $.scojs_message.TYPE_OK);
				$("#dialog_paidan").modal("hide");
				setTimeout(function(){
 					window.location.reload(true);
 				}, 1000);
				
			}else{
				$.scojs_message(data.message, $.scojs_message.TYPE_ERROR);
			}
		});
	}
});
function showClientMaker(lng,lat){
	var point=new BMap.Point(lng,lat);
	paidanMap = new BMap.Map("allmap");  
	paidanMap.centerAndZoom(point, 14);
	paidanMap.enableScrollWheelZoom();
	var marker = new BMap.Marker(point);  // 创建标注
	paidanMap.addOverlay(marker);
	
	paidanMap.addControl(new BMap.MapTypeControl({anchor: BMAP_ANCHOR_TOP_RIGHT, mapTypes: [BMAP_NORMAL_MAP,BMAP_HYBRID_MAP]}));
    
	paidanMap.addControl(new BMap.NavigationControl({anchor: BMAP_ANCHOR_BOTTOM_RIGHT, type: BMAP_NAVIGATION_CONTROL_SMALL}));  //右上角，仅包含平移和缩放按钮
    
    var ctrl = new BMapLib.TrafficControl({
       showPanel: false //是否显示路况提示面板
    });
    paidanMap.addControl(ctrl);
    ctrl.setAnchor(BMAP_ANCHOR_TOP_LEFT);
}
function getDrivers(lng,lat){
	var distance=$("#distance").val();
	var orderId=$("#paidanOrderId").val();
	$.get(ctx+'/driver/freightListDrivers',{'lng':lng,'lat':lat,'distance':distance,'orderId':orderId},function(data){
		if(data && data.length>0){
			$("#paidanDrivers").html('');
			$(data).each(function(i,driver){
				var detailStatus='';
				if(!driver.workCar){
					detailStatus='kongxian';
				}else{
					detailStatus='workcar';
				}
				var htm='<div id="driver_marker_'+driver.id+'" class="sj-mark driver_marker_class" style="position:absolute;z-index:9;">'+
							'<div class="sj-mark-ma sjcolor-'+detailStatus+'"><span>'+driver.realname+'</span></div>'+
							'<div class="sj-mark-rk rkcolor-'+detailStatus+'"></div>'+
					    '</div>';
				if(driver.workCar){
					htm='<div id="driver_marker_'+driver.id+'" class="driver_workcar_marker_class" data-z-index="9998" style="position:absolute;z-index:9998;width:110px;">'+
				        	'<div class="em-'+detailStatus+'-l"></div>'+
				    		'<div class="em-'+detailStatus+'-con">'+driver.realname+'</div>'+
				            '<div class="em-'+detailStatus+'-r"></div>'+
				        '</div>';
				}
			    var driverpoint = new BMap.Point(driver.longitude,driver.latitude);
				var drivermarker = new BMapLib.RichMarker(htm, driverpoint, {"anchor": new BMap.Size(-62, -40), "enableDragging": true});
				drivermarker.driverid=driver.id;
				drivermarker.driverstatus=driver.status;
				paidanMap.addOverlay(drivermarker);
				$("#paidanDrivers").append("<div class='modal-sj-bd' style='display:none;'><button type='button' class='f_detail_paigeita' data-id='"+driver.id+"'>派给</button><span>"+driver.realname+"</span><span>"+driver.phone+"</span><span>"+driver.distanceStr+"</span></div>");
			});
			$(".f_detail_paigeita").each(function(index,element){
        		$(element).parent().fadeIn((index+1)*300);
        	});
		}else{
			$("#paidanDrivers").html(distance+"公里范围内暂无推荐服务人员，您可以扩大范围看看。");
		}
	});
}

Date.prototype.Format = function(fmt) 
{ 
  var o = { 
    "M+" : this.getMonth()+1,                 //月份 
    "d+" : this.getDate(),                    //日 
    "h+" : this.getHours(),                   //小时 
    "m+" : this.getMinutes(),                 //分 
    "s+" : this.getSeconds(),                 //秒 
    "q+" : Math.floor((this.getMonth()+3)/3), //季度 
    "S"  : this.getMilliseconds()             //毫秒 
  }; 
  if(/(y+)/.test(fmt)) 
    fmt=fmt.replace(RegExp.$1, (this.getFullYear()+"").substr(4 - RegExp.$1.length)); 
  for(var k in o) 
    if(new RegExp("("+ k +")").test(fmt)) 
  fmt = fmt.replace(RegExp.$1, (RegExp.$1.length==1) ? (o[k]) : (("00"+ o[k]).substr((""+ o[k]).length)));
  return fmt; 
}